import { VuexModule, Module, Action, getModule, Mutation } from 'vuex-module-decorators'
import { commonAction, deepClone } from '@/utils/common'
import store from '@/store'
function toTree (arr) {
  const list: any = []
  arr.forEach(e => {
    e.disabled = !e.isEnabled
    if (!e.parentId || e.parentId === '0') {
      list.push(e)
    } else {
      const val = arr.find(i => i._id === e.parentId)
      val.children = val.children || []
      val.children.push(e)
    }
  });
  return list
}
function toList (tree) {
  const arr: any[] = []
  flat(tree)
  return arr
  function flat (list, color?: string, fullName = '') {
    for (const i of list) {
      i.color = i.color || color || '#FFFFFF'
      i.disabled = !i.isEnabled
      if (fullName) {
        i.fullName = fullName + '/' + i.name
      } else {
        i.fullName = i.name
      }
      arr.push({
        name: i.name,
        _id: i._id,
        color: i.color,
        parentId: i.parentId,
        isEnabled: i.isEnabled,
        fullName: i.fullName || ''
      })
      if (i.children && i.children.length === 0) {
        delete i.children
      }
      if (i.children && i.children.length) {
        flat(i.children, i.color || color, i.fullName)
      }
    }
  }
}
function del (t, flag) {
  for (let i = 0; i < t.length; i++) {
    if (t[i]?.children) {
      del(t[i].children, flag)
    }
    if (t[i].children && t[i].children.length === 0) {
      delete t[i].children
    }
    if (!t[i].isEnabled && flag) {
      t.splice(i, 1)
      i--
    }
  }
  return t
}

function toObj (arr: any) {
  const obj = {}
  if (arr && arr.length) {
    arr.map((item: any) => {
      obj[item._id] = item
    })
  }

  return obj
}
@Module({ dynamic: true, name: 'tag', store, namespaced: false })
class Tag extends VuexModule {
  public tagTree: any = []
  public tagList: any = []
  public tagMap = new Map()
  public tagAllTree: any = []
  public tagAllObj: any = {}
  @Mutation
  private SET_TAGTREE (tree) {
    this.tagAllTree = del(deepClone(tree), false)
    this.tagList = toList(tree)
    this.tagTree = del(tree, true)
    this.tagAllObj = toObj(this.tagList)
    for (let i = 0; i < this.tagList.length; i++) {
      const e = this.tagList[i]
      this.tagMap.set(e._id, e)
    }
  }

  @Action
  public getTagTree () {
    return commonAction({ url: '/call/action/config/tags/query', method: 'POST', data: {} }).then(res => {
      if (res.success) {
        this.SET_TAGTREE(res.data.tree)
        return res.data.tree || []
      }
    })
  }
}

export const TagModule = getModule(Tag)
